package com.groupbuying.store.service.impl;

import com.groupbuying.store.connector.AdminFeign;
import com.groupbuying.store.connector.FileFegin;
import com.groupbuying.store.connector.SysconfigFeign;
import com.groupbuying.store.constants.CommonConstants;
import com.groupbuying.store.constants.StoreMainInfoEnumConstants;
import com.groupbuying.store.constants.StoreOpexRuleRelPreSearchConstants;
import com.groupbuying.store.dao.StoreCheckoutCounterDao;
import com.groupbuying.store.dao.StoreMainInfoDao;
import com.groupbuying.store.domain.*;
import com.groupbuying.store.dto.StorePhotoDTO;
import com.groupbuying.store.dto.forExternal.StoreCounterInfoDTO;
import com.groupbuying.store.dto.forExternal.StoreShopTempDTO;
import com.groupbuying.store.dto.forExternal.do2dto.StoreShopDetailConvert;
import com.groupbuying.store.dto.forManage.StoreManageExportPageDTO;
import com.groupbuying.store.dto.forManage.StoreOperDTO;
import com.groupbuying.store.dto.forManage.StoreShopAuditPageDTO;
import com.groupbuying.store.dto.forManage.StoreShopManagePageDTO;
import com.groupbuying.store.pojo.StoreMainInfoEnum;
import com.groupbuying.store.service.*;
import com.groupbuying.store.utils.*;
import com.groupbuying.store.utils.apiresult.ApiResult;
import com.groupbuying.store.utils.apiresult.ApiResultCode;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class StoreMainInfoServiceImpl implements StoreMainInfoService {


    private static Logger log = LoggerFactory.getLogger(StoreMainInfoServiceImpl.class);


    @Autowired
    private StoreMainInfoDao storeMainInfoDao;
    @Autowired
    @Lazy
    private StoreCapitalVirtualAccountService storeCapitalVirtualAccountService;
    @Autowired
    @Lazy
    private StoreShopService storeShopService;
    @Autowired
    private StoreCompanyInfoService storeCompanyInfoService;
    @Autowired
    private CompanyQualificationService companyQualificationService;
    @Autowired
    private FileFegin fileFegin;
    @Autowired
    private SysconfigFeign sysconfigFeign;
    @Autowired
    private StoreOpexRuleRelService storeOpexRuleRelService;
    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    private StoreCheckoutCounterService storeCheckoutCounterService;


    @Override
    public StoreMainInfoDO get(String uuid) {
        return storeMainInfoDao.get(uuid);
    }

    @Override
    public List<StoreMainInfoDO> list(Map<String, Object> map) {
        return storeMainInfoDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return storeMainInfoDao.count(map);
    }

    @Override
    public int save(StoreMainInfoDO storeMainInfo) {
        return storeMainInfoDao.save(storeMainInfo);
    }

    @Override
    public int update(StoreMainInfoDO storeMainInfo) {
        return storeMainInfoDao.update(storeMainInfo);
    }

    @Override
    public int remove(String uuid) {
        return storeMainInfoDao.remove(uuid);
    }

    @Override
    public int batchRemove(String[] uuids) {
        return storeMainInfoDao.batchRemove(uuids);
    }

    @Override
    public void updateServShopMainInfo(StoreMainInfoDO storeMainInfoModel, Object customerModel, StoreCapitalVirtualAccountDO virtualModel, StoreShopDO storeShop) {
        //服务门店 不修改商户账号信息，修改的是 会员账号信息
        // 登陆名称 和 手机号,邮箱都不可修改，这里不用操作

        if (virtualModel != null) {
            //1.虚拟资金账户 ，不修改手机号
            virtualModel.setStationuuid(storeMainInfoModel.getStationuuid());
            storeCapitalVirtualAccountService.update(virtualModel);
        }

        //2.修改商户主信息
        this.update(storeMainInfoModel);
        //修改门店信息
        //门店只有 省市区 商圈,人均这几个字段
        storeShop.setShopname(storeMainInfoModel.getStorename());
        //3。修改商户商铺
        if (storeShop != null) {
            storeShopService.update(storeShop);
        }

    }

    @Override
    public List<StoreMainInfoDO> getAllServiceShop(String nowPage, String pageShow) {

        Map param = new HashMap();
        param.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        param.put("offset", Integer.parseInt(nowPage));
        param.put("limit", Integer.parseInt(pageShow));
        param.put("storetype", StoreMainInfoEnum.STORE_TYPE_SERVSHOP);

        List<StoreMainInfoDO> lsStoreMainInfo = storeMainInfoDao.list(param);
        return lsStoreMainInfo;

    }

    @Override
    public void batchUpdate(List<StoreMainInfoDO> stores) {
        storeMainInfoDao.batchUpdate(stores);
    }

    @Override
    public List<StoreMainInfoDO> getStoreListByProviderIdAndAccountId(String nowPage, String pageShow, String userId, String providerId, String storeName, String storeNo) {

        Map map = new HashMap();
        if (StringUtils.isNotBlank(nowPage) && StringUtils.isNotBlank(pageShow)) {
            map.put("offset", Integer.parseInt(nowPage));
            map.put("limit", Integer.parseInt(pageShow));
        }
        map.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        map.put("providerId", providerId);
        map.put("userId", userId);
        map.put("storeName", storeName);
        map.put("storeNo", storeNo);
        return storeMainInfoDao.getStoreListByProviderIdAndAccountId(map);
    }

    @Override
    public List<StoreMainInfoDO> getStoreListByProviderIdAndAccountId(Query query) {
        return storeMainInfoDao.getStoreListByProviderIdAndAccountId(query);
    }

    @Override
    public int getStoreListByProviderIdAndAccountIdCount(Query query) {
        return storeMainInfoDao.getStoreListByProviderIdAndAccountIdCount(query);
    }

    @Override
    public StoreMainInfoDO getByYsCode(String usercode) {

        Map<String, Object> params = new HashMap<>();
        params.put("ysusercode", usercode);
        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        List<StoreMainInfoDO> list = storeMainInfoDao.list(params);
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public R auditStoreShop(Map<String, Object> params) {
        Object temp = params.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        temp = params.get("auditStatus");
        String auditStatus = temp != null ? temp.toString() : null;
        temp = params.get("notPassReason");
        String notPassReason = temp != null ? temp.toString() : "";
        if (StringUtils.isBlank(storeUuid) || StringUtils.isBlank(auditStatus)
                || (StoreMainInfoEnum.AUDIT_NO_PASS.equals(auditStatus) && StringUtils.isBlank(notPassReason))) {
            return R.error("params is null");
        }
        StoreMainInfoDO storeMainInfo = this.get(storeUuid);
        storeMainInfo.setAuditstatus(auditStatus);
        storeMainInfo.setNotpassreason(notPassReason);
        storeMainInfo.setOpetime(DateFormatHelper.getNowTimeStr());

        if (StoreMainInfoEnum.BUSINESS_AUDIT_PASS.equals(auditStatus)) {
            storeMainInfo.setAuditstatus(StoreMainInfoEnum.REPORT_UNDONE);
            Map<String, Object> map = new HashMap<>();
            map.put("storeUuid", storeUuid);
            try {
              Map result = storeShopService.reportYS(map);
              storeMainInfo.setYsnote(result.get("resultMessage").toString());
            } catch (Exception e) {
                e.printStackTrace();
                log.error(e.getMessage());
                storeMainInfo.setYsnote("报备失败，请联系开发人员查明原因");
            }
        }
        this.update(storeMainInfo);

        return R.ok();
    }

    @Override
    public R storeShopDetail(Map<String, Object> params) {
        Object temp = params.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        if (StringUtils.isBlank(storeUuid)) {
            return R.error("params is null");
        }
        StoreMainInfoDO storeMainInfoDO = storeMainInfoDao.get(storeUuid);
        StoreShopDO storeShopDO = storeShopService.getByStoreUuid(storeUuid);
        StoreCompanyInfoDO storeCompanyInfoDO = storeCompanyInfoService.getCompanyInfoByStoreUuid(storeUuid);
        CompanyQualificationDO companyQualificationDO = companyQualificationService.getQualificationByCompanyUuid(storeCompanyInfoDO.getUuid());
        StoreCapitalVirtualAccountDO storeCapitalVirtualAccount = storeCapitalVirtualAccountService.getStoreCapitalVirtualAccountByStoreUuid(storeUuid);

        StorePhotoDTO storePhotoDTO = new StorePhotoDTO();
        String withinphoto = storeShopDO.getWithinphoto();
        if (StringUtils.isNotBlank(withinphoto)) {
            storePhotoDTO.setWithinPhoto(fileFegin.getDownloadUrlByFileGroupKey(withinphoto));
        }
        String doorphoto = storeShopDO.getDoorphoto();
        if (StringUtils.isNotBlank(doorphoto)) {
            storePhotoDTO.setDoorPhoto(fileFegin.getDownloadUrlByFileGroupKey(doorphoto));
        }
        String legalidcard1 = storeCompanyInfoDO.getLegalidcard1();
        if (StringUtils.isNotBlank(legalidcard1)) {
            storePhotoDTO.setLegalidCard1(fileFegin.getDownloadUrlByFileGroupKey(legalidcard1));
        }
        String legalidcard2 = storeCompanyInfoDO.getLegalidcard2();
        if (StringUtils.isNotBlank(legalidcard2)) {
            storePhotoDTO.setLegalidCard2(fileFegin.getDownloadUrlByFileGroupKey(legalidcard2));
        }
        String settle1image = storeCompanyInfoDO.getSettle1image();
        if (StringUtils.isNotBlank(settle1image)) {
            storePhotoDTO.setSettle1Image(fileFegin.getDownloadUrlByFileGroupKey(settle1image));
        }
        String settle2image = storeCompanyInfoDO.getSettle2image();
        if (StringUtils.isNotBlank(settle2image)) {
            storePhotoDTO.setSettle2Image(fileFegin.getDownloadUrlByFileGroupKey(settle2image));
        }
        String bussinesslicensephoto = companyQualificationDO.getBussinesslicensephoto();
        if (StringUtils.isNotBlank(bussinesslicensephoto)) {
            storePhotoDTO.setBussinessLicensePhoto(fileFegin.getDownloadUrlByFileGroupKey(bussinesslicensephoto));
        }
        String agreementimage = storeCompanyInfoDO.getAgreementimage();
        if (StringUtils.isNotBlank(agreementimage)) {
            storePhotoDTO.setAgreementImage(fileFegin.getDownloadUrlByFileGroupKey(agreementimage));
        }
        String slideshow = storeShopDO.getSlideshow();
        if (StringUtils.isNotBlank(slideshow)) {
            storePhotoDTO.setSlideshow(fileFegin.getDownloadUrlByFileGroupKey(slideshow));
        }
        String authorizationletter = storeCompanyInfoDO.getAuthorizationletter();
        if (StringUtils.isNotBlank(authorizationletter)) {
            storePhotoDTO.setAuthorizationLetter(fileFegin.getDownloadUrlByFileGroupKey(authorizationletter));
        }
        String licenseimage = storeCompanyInfoDO.getLicenseimage();
        if (StringUtils.isNotBlank(licenseimage)) {
            storePhotoDTO.setLicenseimage(fileFegin.getDownloadUrlByFileGroupKey(licenseimage));
        }
        Map<String, Object> result = new HashMap<>();
        result.put("storeMainInfo", storeMainInfoDO);
        result.put("storeShop", storeShopDO);
        result.put("storeCompanyInfo", storeCompanyInfoDO);
        result.put("companyQualification", companyQualificationDO);
        result.put("storeCapitalVirtualAccount", storeCapitalVirtualAccount);
        result.put("storePhotoDTO", storePhotoDTO);


        return R.ok(result);
    }

    @Override
    public R getListByPage(Map<String, Object> params) {

        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("sort", "createOpeTime");
        params.put("order", "desc");


        Query query = new Query(params);
        List<StoreShopAuditPageDTO> smi = storeMainInfoDao.getListByPage(query);
        Map<String, Object> feignParam = new HashMap<>();
        for (StoreShopAuditPageDTO storeShopAuditPage : smi) {
            feignParam.clear();
            feignParam.put("agentId", storeShopAuditPage.getAgentId());
            String jsonResult = adminFeign.queryAgent(feignParam);
            Map feignResult = JSONUtils.jsonToMap(jsonResult);
            String province = feignResult.get("province") != null ? feignResult.get("province").toString() : "";
            String city = feignResult.get("city") != null ? feignResult.get("city").toString() : "";
            String district = feignResult.get("district") != null ? feignResult.get("district").toString() : "";

            storeShopAuditPage.setAgentCity(String.format("%s  %s %s", province, city, district));
            storeShopAuditPage.setAgentName(feignResult.get("agentName").toString());
        }

        //int total = this.count(query);
        params.remove("limit");
        params.remove("page");
        query = new Query(params);
        List<StoreShopAuditPageDTO> totalList = storeMainInfoDao.getListByPage(query);
        PageUtils pageUtil = new PageUtils(smi, totalList.size());
        return R.ok().put("page", pageUtil);
    }

    @Override
    public R getListByManagePage(Map<String, Object> params) {
        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("sort", "createOpeTime");
        params.put("order", "desc");

        Object temp = params.get("province");
        String provinceParam = temp != null ? temp.toString() : "";
        temp = params.get("city");
        String cityParam = temp != null ? temp.toString() : "";
        temp = params.get("district");
        String districtParam = temp != null ? temp.toString() : "";

        if (StringUtils.isNotBlank(provinceParam) || StringUtils.isNotBlank(cityParam) || StringUtils.isNotBlank(districtParam)) {
            List<Map> feignResultList = getAgentByArea(provinceParam, cityParam, districtParam);
            if (feignResultList != null && feignResultList.size() > 0) {
                params.put("agents", feignResultList);
            } else {
                //没有存在的地区值，直接返回
                return R.ok().put("page", new PageUtils(new ArrayList<StoreShopManagePageDTO>(), 0));
            }
        }

        Query query = new Query(params);
        List<StoreShopManagePageDTO> smi = storeMainInfoDao.getListByManagePage(query);

        Map<String, Object> feignParam = new HashMap<>();
        for (StoreShopManagePageDTO storeShopManagePage : smi) {
            feignParam.clear();
            feignParam.put("agentId", storeShopManagePage.getAgentId());
            String jsonResult = adminFeign.queryAgent(feignParam);
            Map feignResult = null;
            if (StringUtils.isNotBlank(jsonResult)) {
                feignResult = JSONUtils.jsonToMap(jsonResult);
                String province = feignResult.get("province") != null ? feignResult.get("province").toString() : "";
                String district = feignResult.get("district") != null ? feignResult.get("district").toString() : "";
                String city = feignResult.get("city") != null ? feignResult.get("city").toString() : "";
                storeShopManagePage.setAgentCity(String.format("%s  %s %s", province, city, district));
                storeShopManagePage.setAgentName(feignResult.get("agentName").toString());

            }
            storeShopManagePage.setStoreSubsidyRate(new BigDecimal(storeShopManagePage.getStoreSubsidyRate()).multiply(new BigDecimal("100")).setScale(1,BigDecimal.ROUND_HALF_UP).toString());
        }

        params.remove("limit");
        params.remove("page");
        query = new Query(params);
        List<StoreShopManagePageDTO> totalList = storeMainInfoDao.getListByManagePage(query);
        PageUtils pageUtil = new PageUtils(smi, totalList.size());
        return R.ok().put("page", pageUtil);

    }

    @Override
    public R freezeOrUnfreezeStoreShop(Map<String, Object> params) {

        Object temp = params.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        temp = params.get("freezeStatus");
        String freezeStatus = temp != null ? temp.toString() : null;
        temp = params.get("freezeReason");
        String freezeReason = temp != null ? temp.toString() : "";
        if (StringUtils.isBlank(storeUuid) || StringUtils.isBlank(freezeStatus)
                || (StoreMainInfoEnum.FROZEN.equals(freezeStatus) && StringUtils.isBlank(freezeReason))) {
            return R.error("params is null");
        }
        StoreMainInfoDO storeMainInfo = this.get(storeUuid);
        storeMainInfo.setFreezestatus(freezeStatus);
        storeMainInfo.setFreezereason(freezeReason);
        String timeStamp = DateFormatHelper.getNowTimeStr();
        storeMainInfo.setOpetime(timeStamp);
        storeMainInfo.setFreezetime(timeStamp);
        this.update(storeMainInfo);
        return R.ok();
    }

    @Override
    public R getShopDetail(Map<String, Object> params) {

        Object temp = params.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : null;
        if (StringUtils.isBlank(storeUuid)) {
            return R.error("params is null");
        }
        StoreMainInfoDO storeMainInfoDO = storeMainInfoDao.get(storeUuid);
        StoreShopDO storeShopDO = storeShopService.getByStoreUuid(storeUuid);

        if (storeShopDO == null) {
            R.error();
        }

        Map queryCounterParam = new HashMap();
        queryCounterParam.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        queryCounterParam.put("storeuuid", storeUuid);
        List<StoreCheckoutCounterDO> checkoutCounterDOList = storeCheckoutCounterService.list(queryCounterParam);
        String counterId = checkoutCounterDOList != null && checkoutCounterDOList.size() > 0 ? checkoutCounterDOList.get(0).getUuid(): null;

        StorePhotoDTO storePhotoDTO = new StorePhotoDTO();
        storePhotoDTO.setWithinPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShopDO.getWithinphoto()));
        storePhotoDTO.setDoorPhoto(fileFegin.getDownloadUrlByFileGroupKey(storeShopDO.getDoorphoto()));
        storePhotoDTO.setSlideshow(fileFegin.getDownloadUrlByFileGroupKey(storeShopDO.getSlideshow()));

        Map<String, Object> result = new HashMap<>();
        StoreShopTempDTO storeShopTempDTO = new StoreShopTempDTO();
        storeShopTempDTO.setStoreMainInfoDO(storeMainInfoDO);
        storeShopTempDTO.setStoreShopDO(storeShopDO);
        result.put("storePhotoDTO", storePhotoDTO);
        result.put("shopDetail", StoreShopDetailConvert.MAPPER.dTOToDTO(storeShopTempDTO));
        result.put("counterId",counterId);

        Map searchMap = new HashMap();
        searchMap.put(StoreOpexRuleRelPreSearchConstants.SEARCH_STOREID,storeUuid);
        searchMap.put(StoreOpexRuleRelPreSearchConstants.SEARCH_DELFLAG,CommonConstants.COMMON_FLAG_UNDEL);
        List <StoreOpexRuleRelDO> listOpex = storeOpexRuleRelService.list(searchMap);



        if (listOpex == null || listOpex.size() == 0) {
            return R.ok(result);
        }

        StoreOpexRuleRelDO storeOpexRuleRelDO = listOpex.get(0);
        Map ruleMap = new HashMap();
        ruleMap.put("ruleId", storeOpexRuleRelDO.getRuleId());
        ruleMap.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
        Map ruleRes = sysconfigFeign.getStoreOpexRule(ruleMap);
        if (ruleRes != null) {
            BigDecimal backCurrency = new BigDecimal(ruleRes.get("backCurrencyRatio").toString());
            BigDecimal discount = new BigDecimal(ruleRes.get("currencyPayDiscount").toString());
            discount = discount.divide(new BigDecimal(10));
            result.put("ratio", backCurrency);
            result.put("discount", discount);
            result.put("ruleId", storeOpexRuleRelDO.getRuleId());
            result.put("ruldeDes", storeOpexRuleRelDO.getRuleDes());
        }
        return R.ok(result);
    }


    @Override
    public List<Map<String, String>> getUuidAndStoreName() {
        return storeMainInfoDao.getUuidAndStoreName();
    }

    @Override
    public R getStoreOperList(Map<String, Object> params) {
        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("sort", "createOpeTime");
        params.put("order", "desc");
        Query query = new Query(params);
        List<StoreOperDTO> smi = storeMainInfoDao.getStoreOperList(query);
        params.remove("limit");
        params.remove("page");
        query = new Query(params);
        List<StoreOperDTO> totalList = storeMainInfoDao.getStoreOperList(query);
        PageUtils pageUtil = new PageUtils(smi, totalList.size());
        return R.ok().put("page", pageUtil);
    }

    @Override
    public R setStoreOper(Map<String, Object> params) {
        Object temp = params.get("storeUuid");
        String storeUuid = temp != null ? temp.toString() : "";
        temp = params.get("operateMan");
        String operateMan = temp != null ? temp.toString() : "";
        temp = params.get("operateTel");
        String operateTel = temp != null ? temp.toString() : "";
        temp = params.get("operateNote");
        String operateNote = temp != null ? temp.toString() : "";

        StoreMainInfoDO storeMainInfoDO = storeMainInfoDao.get(storeUuid);
        if (storeMainInfoDO == null) {
            return R.error();
        }
        storeMainInfoDO.setOperateman(operateMan);
        storeMainInfoDO.setOperatetel(operateTel);
        storeMainInfoDO.setWeixin(operateNote);

        storeMainInfoDao.update(storeMainInfoDO);
        return R.ok();
    }

    @Override
    public Map getStoreInfoByCounterUuid(String counterUuid) {
        return storeMainInfoDao.getStoreInfoByCounterUuid(counterUuid);
    }

    /**
     * 通过门店编辑费率
     */
    @Override
    public ApiResult setRate(Map<String, Object> condMap) {
        ApiResult assembleResult =   assembleParams(condMap);
        if(!ApiResultCode.SUCCESS.code().equals(assembleResult.getCode())){
            return assembleResult;
        }
        Map<String,Object> paramsMap = (Map<String, Object>) assembleResult.getResult();
        if (storeMainInfoDao.setRate(paramsMap) > 0) {
            return ApiResult.success();
        } else {
            return ApiResult.failure(ApiResultCode.OPRFAILURE);
        }
    }

    @Override
    public R getExportStoreMangeList(Map<String, Object> params) {

        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("auditStatus", StoreMainInfoEnum.BUSINESS_AUDIT_PASS);
        params.put("sort", "createOpeTime");
        params.put("order", "desc");

        Object temp = params.get("province");
        String province = temp != null ? temp.toString() : "";
        temp = params.get("city");
        String city = temp != null ? temp.toString() : "";
        temp = params.get("district");
        String district = temp != null ? temp.toString() : "";

        if (StringUtils.isNotBlank(province) || StringUtils.isNotBlank(city) || StringUtils.isNotBlank(district)) {
            List<Map> feignResultList = getAgentByArea(province, city, district);
            if (feignResultList != null && feignResultList.size() > 0) {
                params.put("agents", feignResultList);
            } else {
                //没有存在的地区值，直接返回
                return R.ok().put("page", new PageUtils(new ArrayList<StoreManageExportPageDTO>(), 0));
            }

        }

        Query query = new Query(params);
        List<StoreManageExportPageDTO> storeManageExportPageDTOList = storeMainInfoDao.getExportStoreMangeList(query);
        Map<String, Object> feignParam = new HashMap<>();
        for (StoreManageExportPageDTO storeManageExportPageDTO : storeManageExportPageDTOList) {
            feignParam.clear();
            feignParam.put("agentId", storeManageExportPageDTO.getAgentId());
            String jsonResult = adminFeign.queryAgent(feignParam);
            Map feignResult = null;
            if (StringUtils.isNotBlank(jsonResult)) {
                feignResult = JSONUtils.jsonToMap(jsonResult);
                storeManageExportPageDTO.setAgentName(feignResult.get("agentName").toString());
            }

            switch (storeManageExportPageDTO.getFreezeStatus()) {

                case StoreMainInfoEnum.FROZEN: {
                    storeManageExportPageDTO.setFreezeStatus("已冻结");
                }
                break;
                case StoreMainInfoEnum.UNFROZEN: {
                    storeManageExportPageDTO.setFreezeStatus("未冻结");
                }
                break;
            }

        }

        return R.ok().put("page", storeManageExportPageDTOList);
    }

    @Override
    public R getListByPageInFinance(Map<String, Object> params) {
        params.put("delflag", CommonConstants.COMMON_FLAG_UNDEL);
        params.put("sort", "createOpeTime");
        params.put("order", "desc");


        Query query = new Query(params);
        List<StoreShopAuditPageDTO> smi = storeMainInfoDao.getListByPageInFinance(query);
        Map<String, Object> feignParam = new HashMap<>();
        for (StoreShopAuditPageDTO storeShopAuditPage : smi) {
            feignParam.clear();
            feignParam.put("agentId", storeShopAuditPage.getAgentId());
            String jsonResult = adminFeign.queryAgent(feignParam);
            Map feignResult = JSONUtils.jsonToMap(jsonResult);
            String province = feignResult.get("province") != null ? feignResult.get("province").toString() : "";
            String city = feignResult.get("city") != null ? feignResult.get("city").toString() : "";
            String district = feignResult.get("district") != null ? feignResult.get("district").toString() : "";

            storeShopAuditPage.setAgentCity(String.format("%s  %s %s", province, city, district));
            storeShopAuditPage.setAgentName(feignResult.get("agentName").toString());
        }

        //int total = this.count(query);
        params.remove("limit");
        params.remove("page");
        query = new Query(params);
        List<StoreShopAuditPageDTO> totalList = storeMainInfoDao.getListByPage(query);
        PageUtils pageUtil = new PageUtils(smi, totalList.size());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 通过地区获取代理商
     *
     * @param province
     * @param city
     * @param district
     * @return
     */
    private List<Map> getAgentByArea(String province, String city, String district) {
        Map areaParam = new HashMap();
        if(province != null && province!=""){
            areaParam.put("province", province);
        }
        if(city != null && city!=""){
            areaParam.put("city", city);
        }
        if(district != null && district!="") {
            areaParam.put("district", district);
        }
        String jsonResult = adminFeign.queryAgentByArea(areaParam);
        List<Map> feignResultList = null;
        if (StringUtils.isNotBlank(jsonResult)) {
            feignResultList = (List<Map>) JSONUtils.jsonToBean(jsonResult, new ArrayList());
            log.error("根据地区查询代理商结果：{}", jsonResult);
        }
        return feignResultList;
    }

    private ApiResult assembleParams(Map params){
        log.error("StoreMainInfoServiceImpl setRate assembleParams params:::"+params);
        boolean flag =ParamUtils.checkSetRateParams(params);
        if(!flag){
            log.error("StoreMainInfoServiceImpl setRate assembleParams params is illegal"+params);
            return ApiResult.paramIsllegal();
        }
        //type: 现金:1,余额,2
        int type = (int) params.get("type");
        Map<String,Object> returnMap = new HashMap<>();
        returnMap.put("storeUuid",params.get("storeUuid"));
        returnMap.put("opeTime", DateFormatHelper.getNowTimeStr());
        if(type == 1){
            String storeRate = params.get("storeRate")== null ? "":(String) params.get("storeRate");
            BigDecimal rate = StringUtils.isEmpty(storeRate)?null:(new BigDecimal(storeRate).divide(new BigDecimal("1000"))).setScale(4,BigDecimal.ROUND_HALF_UP);
            returnMap.put("rate",rate);
        }else if(type == 2){
            String balanceRate =params.get("balanceRate") == null?"":(String) params.get("balanceRate");
            BigDecimal storeSubsidyRate = StringUtils.isEmpty(balanceRate)?null:(new BigDecimal(balanceRate).divide(new BigDecimal("100"))).setScale(3,BigDecimal.ROUND_HALF_UP);
            returnMap.put("storeSubsidyRate",storeSubsidyRate);
        }else{
            return ApiResult.failure(ApiResultCode.PARAMERROR);
        }
        return ApiResult.success(returnMap);
    }
}
